package gamagora.game.map
{
	import gamagora.box2d.OSPhysicSprite;
	
	import org.flixel.FlxBasic;
	import org.flixel.FlxGroup;
	import org.flixel.FlxSprite;

	public class OSMap
	{
		public static const WIDTH:uint = 960;
		public static const HEIGHT:uint = 1080;
		
		protected var _xDecal:uint;
		protected var _objects:Vector.<OSPhysicSprite>;
		protected var _inGame:Boolean;
		protected var _nbObjects:uint;
		
		//Layers
		protected var _backgrounds:FlxGroup;
		protected var _foregrounds:FlxGroup;
		
		public function OSMap(xDecal:uint = 0)
		{
			_xDecal = xDecal * WIDTH;
			_objects = new Vector.<OSPhysicSprite>();
			
			_backgrounds = new FlxGroup();
			_foregrounds = new FlxGroup();
			
			create();
			
			_nbObjects = _objects.length;
		}
		
		protected function create():void
		{
		}
		
		public function draw():void
		{
			for(var i:uint=0;i<_nbObjects;i++)
			{
				if(_objects[i].visible)
				{
					_objects[i].draw();
				}
			}
		}
		
		public function drawBackgrounds():void
		{
			_backgrounds.draw();
		}
		
		public function drawForegrounds():void
		{
			_foregrounds.draw();
		}
		
		public function pushObjects(group:FlxGroup):uint
		{
			var nbSprites:uint = 0;
			
			for(var i:uint=0;i<_nbObjects;i++)
			{
				_objects[i].create(group);
				group.add(_objects[i]);
				nbSprites += _objects[i].nbSprites;
			}
			
			group.add(_backgrounds);
			nbSprites += _backgrounds.length;
			
			group.add(_foregrounds);
			nbSprites += _foregrounds.length;
			
			_inGame = true;
			
			return nbSprites;
		}
		
		public function removeObjects(group:FlxGroup):uint
		{
			var nbSprites:uint = 0;
			
			for(var i:uint=0;i<_nbObjects;i++)
			{
				group.remove(_objects[i], true);
				nbSprites += _objects[i].nbSprites;
				_objects[i].destroyPhysic();
			}
			
			group.remove(_backgrounds, true);
			nbSprites += _backgrounds.length;
			
			group.remove(_foregrounds, true);
			nbSprites += _foregrounds.length;
			
			_inGame = false;
			
			return nbSprites;
		}
		
		public function leftClosed(x:Number, limit:uint = 50):Boolean
		{
			return x >= _xDecal - limit;
		}
		
		public function rightClosed(x:Number, limit:uint = 50):Boolean
		{
			return x <= _xDecal + WIDTH + limit;
		}
		
		public function inside(x:Number):Boolean
		{
			return x >= _xDecal && x <= _xDecal + WIDTH;
		}
			
		//Getters Setters

		public function get xDecal():uint
		{
			return _xDecal;
		}

		public function get inGame():Boolean
		{
			return _inGame;
		}
	}
}
